package com.njupt.hibernate;

import org.hibernate.cfg.ImprovedNamingStrategy;


public class PrefixImprovedNamingStrategy extends ImprovedNamingStrategy{

	private String tablePrefix;
	private String columnPrefix;
	private Integer maxLength;
	
	public String propertyToColumnName(String propertyName) {
		String n = columnPrefix + super.propertyToColumnName(propertyName);
		if(maxLength != null){
			if(n.length() > maxLength)
				n = shortIt(n,columnPrefix.length());
		}
		return n;
	}
	public String classToTableName(String className) {
		String n = tablePrefix + super.classToTableName(className);
		if(maxLength != null){
			if(n.length() > maxLength)
			n = shortIt(n,tablePrefix.length());
		}
		return n;
	}
	private String shortIt(String oriName,int prefixLength){
		String[] segments = oriName.split("_");
		int segLength = (maxLength-prefixLength-segments.length+1)/(segments.length-1);
		String newStr = segments[0];
		for(int i = 1; i < segments.length; i++){
			if(segments[i].length()>segLength){
				segments[i] = segments[i].substring(0,segLength);
			}
			newStr += "_"+segments[i];
		}
		return newStr;
	}
	public String getTablePrefix() {
		return tablePrefix;
	}
	public void setTablePrefix(String tablePrefix) {
		this.tablePrefix = tablePrefix;
	}
	public String getColumnPrefix() {
		return columnPrefix;
	}
	public void setColumnPrefix(String columnPrefix) {
		this.columnPrefix = columnPrefix;
	}
	public Integer getMaxLength() {
		return maxLength;
	}
	public void setMaxLength(Integer maxLength) {
		this.maxLength = maxLength;
	}
}

